<?php
/**
 * Created by PhpStorm.
 * User: sqq
 * Date: 2018/07/24
 * Time: 14:03
 */

class ApiCarController extends BaseController {

    /**
     * @Author:      sqq
     * @DateTime:    2018-07-25 19:01:44
     * @Description: C端3.0 车辆年款
     * @param int $series_id    车系－名称－ID
     * @param int series_shop_id    车系－厂商－ID
     * @link http://www.activity.com/wechat/api3.0/modelYear?series_id=4241&series_shop_id=1
     */
    public function modelYear(){
        $validator = Validator::make(Input::all(),
            array(
                'series_id' => 'required',
                'series_shop_id' => 'required',
            )
        );
        do{
            if($validator->fails()){
                $response = Lang::get("error.args_error_10000");
                $response['result'] = $validator->messages()->all();
                break;
            }
            $model_year = DataCarStandardInfo::where('series_shop_id',Input::get('series_shop_id'))
                ->where('series_name_id',Input::get('series_id'))
                ->where('status',1)
                ->select('model_year')
                ->distinct()
                ->get();
            $response = array(
                "code" => 0,
                "msg" => "ok",
                "result" => $model_year,
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "modelYear", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-25 19:04:28
     * @Description: 车辆型号
     * @param int $series_id        车系－名称－ID
     * @param int series_shop_id    车系－厂商－ID
     * @param int model_year        车型－年款
     * @link http://www.activity.com/wechat/api3.0/modelName?series_id=4241&series_shop_id=1&model_year=2017%E6%AC%BE
     */
    public function modelName(){
        $validator = Validator::make(Input::all(),
            array(
                'series_id' => 'required',
                'series_shop_id' => 'required',
                'model_year' => 'required',
            )
        );
        do{
            if($validator->fails()){
                $response = Lang::get("error.args_error_10000");
                $response['result'] = $validator->messages()->all();
                break;
            }
            $model_name = DataCarStandardInfo::where('series_shop_id',Input::get('series_shop_id'))
                ->where('series_name_id',Input::get('series_id'))
                ->where('model_year',Input::get('model_year'))
                ->where('status',1)
                ->select([
                    'model_name',
                    'id',
                    'brand_name_id as brand_id',
                    'series_shop_id',
                    'series_name_id',
                ])
                ->get();
            $response = array(
                "code" => 0,
                "msg" => 'ok',
                "result" => $model_name
            );
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "modelName", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-26 09:12:28
     * @Description: 换车列表
     * @param  $token   用户token
     * @link   http://www.activity.com/wechat/api3.0/carList?token=2628d9f5d95ea4f138cbb9f68931a586
     */
    public function carList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //根据用户id获取用户的所有车辆（优先展示默认车辆）[排序方式：默认 > id]
            $detail_car = UserCarInfo::join('anhui_data.car_brand','user_car_info.car_brand_id','=','anhui_data.car_brand.id')
                ->join('anhui_data.car_standard_info','anhui_data.car_standard_info.id','=','user_car_info.car_model_id')
                ->leftJoin('user_car_info_inquiry','user_car_info.id','=','user_car_info_inquiry.user_car_info_id')
                ->where('user_car_info.user_id',$users->id)
                ->whereIn('user_car_info.status',[1,3])
                ->select('user_car_info.id','user_car_info.is_default','anhui_data.car_brand.name','anhui_data.car_brand.icon','user_car_info.car_no','anhui_data.car_standard_info.model_name','anhui_data.car_standard_info.model_year','anhui_data.car_standard_info.series_name','user_car_info.is_lock','user_car_info.car_model_id','anhui_data.car_standard_info.brand_name_id as car_brand_id','anhui_data.car_standard_info.series_name_id as car_series_id','anhui_data.car_standard_info.series_shop_id','user_car_info_inquiry.id as car_id','user_car_info.is_default')
                ->orderBy('is_default', 'desc')
                ->orderBy('user_car_info.id','asc')
                ->get()->toArray();
//            $carList = "";
//            if(!is_null($detail_car)){
//                foreach($detail_car as $_key => $_val){
//                    $_val['url'] = Config::get('config.car_brand_img_url');
//                    if($_val['is_default'] == 1){
//                        $detail = $detail_car[$_key];
//                    }else{
//                        $carList[] = $detail_car[$_key];
//                    }
//                }
//                array_unshift($carList,$detail);
////                if(!$detail){
////                    array_unshift($carList,$detail);
////                }
//            }

            if(!empty($detail_car)){
                foreach($detail_car as $_key => $_val){
                    $detail_car[$_key]['car_brand_img_url'] = Config::get('config.car_brand_img_url');
                    $detail_car[$_key]['APP_weizhan_service_url'] = Config::get('config.APP_weizhan_service_url');
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => $detail_car);
        }while(false);
        Log::info("info", array("system" => "api3.0" ,"event" => "carList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-26 10:57:28
     * @Description: 添加车辆
     * @param  $token   用户token
     * @link    www.activity.com/wechat/api3.0/addServiceCar?token=301fa556cf7509819b36db43fb4df384&car_brand_id=31&car_series_id=633&car_model_id=29597&is_default=0&icon=http://pic.yangche1hao.com/cms/carbrand/1449574264-24189.png&brand_name=大众&series_name=宝来&model_year=2018款&model_name=2018款 1.5L 手动舒适型&car_no=A111111&user_car_id=345787&car_braand_img_url=http://pic.yangche1hao.com/cms/carbrand/&car_id=345787&short_name=京
     */
    public function addServiceCar(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_brand_id' => 'required',
                'car_series_id' => 'required',
                'car_model_id' => 'required',
                'is_default' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //验证token
            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //传入参数
            $token = Input::get('token');
            $car_brand_id = Input::get('car_brand_id');
            $car_series_id = Input::get('car_series_id');
            $car_model_id = Input::get('car_model_id');
            $is_default = Input::get('is_default',0);
            $car_no = Input::get('car_no');
            $short_name = Input::get('short_name');
            $mileage = Input::get('mileage');
            $start_off_time = Input::get('start_off_time');
            $car_level = Input::get('car_level',0);
            $vin = Input::get('vin','');
            $engine_number = Input::get('engine_number');
            $registrationTime = Input::get('registration_time');
            $type = Input::get('type');
            $is_lock = Input::get('is_lock');

            //询价用户车辆信息
            try{
                //if(isset($car_no) && !empty($car_no) && isset($short_name) && !empty($short_name)) {
                if(preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $short_name)<=0){
                    return json_encode(array('code' => 100332, 'msg' => '车牌号首字符不是中文'));break;
                }
                if($car_no && $short_name) {
                    $car_data = UserCarInfo::where('user_id', $users->id)->where('car_no', $short_name . $car_no)->where('status',1)->first();
                    if($type == 1 && !is_null($car_data)){
                        return json_encode(array('code' => 100313, 'msg' => '车牌号已存在'));break;
                    }
                    if (is_null($car_data)) {
                        $car_data = new UserCarInfo;
                    }
                    $car_data->user_id = $users->id;
                    $car_data->car_brand_id = $car_brand_id;
                    $car_data->car_series_id = $car_series_id;
                    $car_data->car_model_id = $car_model_id;
//                    if ($is_default == 1) {
//                        UserCarInfo::where('user_id', $users->id)
//                            ->where('status', 1)
//                            ->update(array('is_default' => 0));
//                    }
                    $car_data->is_default = $is_default;
                    if($vin){
                        $car_data->vin_code = $vin;
                    }
                    $car_data->status = 1;
                    if(!empty($short_name) && $short_name != '' && !empty($car_no) && $car_no != ''){
                        $car_data->car_no = $short_name.$car_no;
                    }
                    if($mileage){
                        $car_data->mileage = $mileage;
                    }
                    if($start_off_time){
                        $car_data->start_off_time = $start_off_time;
                    }
                    if($car_level){
                        $car_data->car_level = $car_level;
                    }
                    if($is_lock){
                        $car_data->is_lock = 0;
                    }
                    $car_data->save();

                    $car = UserCarInfoInquiry::where('user_id', $users->id)->where('car_no', $short_name . $car_no)->where('status',1)->first();
                    if (is_null($car)) {
                        $car = new UserCarInfoInquiry();
                    }
                    $car->user_car_info_id = $car_data->id;
                    $car->user_id = $users->id;
                    $car->car_brand_id = $car_brand_id;
                    $car->car_series_id = $car_series_id;
                    $car->car_model_id = $car_model_id;
//                    if($is_default == 1){
//                        UserCarInfoInquiry::where('user_id',$users->id)
//                            ->where('status',1)
//                            ->update(array('is_default' => 0));
//                    }
                    $car->is_default = $is_default;
                    $car->status = 1;
                    if(!empty($short_name) && $short_name != '' && !empty($car_no) && $car_no != ''){
                        $car->car_no = $short_name.$car_no;
                    }
                    if($mileage){
                        $car->mileage = $mileage;
                    }
                    if($start_off_time){
                        $car->start_off_time = $start_off_time;
                    }
                    if($car_level){
                        $car->car_level = $car_level;
                    }
                    if($is_lock){
                        $car->is_lock = 0;
                    }
                    if($vin){
                        $car->vin_code = $vin;
                    }
                    if($engine_number){
                        $car->engine_number = $engine_number;
                    }
                    if($registrationTime){
                        $car->registration_time = $registrationTime;
                    }
                    $car->save();
                }else{
                    $car = UserCarInfoInquiry::where('user_id', $users->id)->where('car_brand_id',$car_brand_id)->where('car_series_id',$car_series_id)->where('car_model_id',$car_model_id)->where('status',1)->first();
                    if(is_null($car)){
                        $car = new UserCarInfoInquiry();
                    }
                    $car->user_id = $users->id;
                    $car->car_brand_id = $car_brand_id;
                    $car->car_series_id = $car_series_id;
                    $car->car_model_id = $car_model_id;
                    if($is_default == 1){
                        UserCarInfoInquiry::where('user_id',$users->id)
                            ->where('status',1)
                            ->update(array('is_default' => 0));
                    }
                    $car->is_default = $is_default;
                    $car->status = 1;
                    if(!empty($short_name) && $short_name != '' && !empty($car_no) && $car_no != ''){
                        $car->car_no = $short_name.$car_no;
                    }
                    if($mileage){
                        $car->mileage = $mileage;
                    }
                    if($start_off_time){
                        $car->start_off_time = $start_off_time;
                    }
                    if($car_level){
                        $car->car_level = $car_level;
                    }
                    if($is_lock){
                        $car->is_lock = 0;
                    }
                    if($vin){
                        $car->vin_code = $vin;
                    }
                    if($engine_number){
                        $car->engine_number = $engine_number;
                    }
                    if($registrationTime){
                        $car->registration_time = $registrationTime;
                    }
                    $car->save();
                }

                $response = array('code' => 0, 'msg' => 'ok', 'result' => array('car_id' => $car->id, 'user_car_id' => $car->user_car_info_id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "api3.0" ,"event" => "addServiceCar", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_car_add_error_1006");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "api3.0" ,"event" => "addServiceCar", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-07-26 10:57:28
     * @Description: 解绑车辆
     * @param  $token   用户token
     * @link：http://www.activity.com/wechat/api3.0/delCar?token=301fa556cf7509819b36db43fb4df384&id=9096
     */
    public function delCar(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //验证token
            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //传入参数
            $id = Input::get('id');

            try{
                $service_card = ServiceCardCar::where('user_id',$users->id)->where('id',$id)->first();
                if(empty($service_card)){
                    $response = Lang::get("error.user_car_not_exit_error_1019");
                    break;
                }
                $service_card->status = 0;
                $service_card->updated_at = Common::currentTimeString();
                $service_card->save();
                $response = array('code' => 0, 'msg' => 'ok');
            } catch (Exception $e) {
                Log::error("error", array("system" => "api3.0" ,"event" => "delCar", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_car_add_error_1006");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "api3.0" ,"event" => "delCar", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-08-17 16:44:28
     * @Description: 更改默认车辆
     * @param  $token   String   用户token
     * @param  $id   String   车辆id
     * @link:
     */
    public function defaultCar(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("error.args_error_1000");
                $response["result"]=$validator->messages()->all();
                break;
            }

            //验证token
            $users=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($users)){
                break;
            }

            //传入参数
            $token = Input::get('token');
            $id = Input::get('id');//user_car_info表id

            //询价用户车辆信息
            try{
                UserCarInfo::where('user_id',$users->id)
                    ->where('status',1)
                    ->update(array('is_default' => 0));
                UserCarInfo::where('user_id',$users->id)
                    ->where('status',1)
                    ->where('id',$id)
                    ->update(array('is_default' => 1));
                UserCarInfoInquiry::where('user_id',$users->id)
                    ->where('status',1)
                    ->update(array('is_default' => 0));
                UserCarInfoInquiry::where('user_id',$users->id)
                    ->where('status',1)
                    ->where('user_car_info_id',$id)
                    ->update(array('is_default' => 1));

                $response = array('code' => 0, 'msg' => 'ok');
            } catch (Exception $e) {
                Log::error("error", array("system" => "api3.0" ,"event" => "defaultCar", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("error.user_car_add_error_1006");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "api3.0" ,"event" => "defaultCar", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


}